<template>
  <upload-excel :on-success="handleSuccess" />
</template>

<script>
import { reqImportEmployee } from '@/api/employees'
export default {
  name: 'Import',
  computed: {
    type() {
      return this.$route.query.type
    }
  },
  mounted() {
    // console.log('66', this.$route)
    // console.log(this.formatExcelDate(43535, '-'))
  },
  methods: {
    isLeapYear(year) {
      return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0
    },
    // 处理excel传入的时间问题
    formatExcelDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1) // 毫秒
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() + ''

      // 判断闰年
      if (this.isLeapYear(year)) {
        this.date = date - 1
      }
      if (format && format.length === 1) {
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    },
    async handleSuccess({ header, results }) {
      if (this.type === 'user') {
        const userRelations = {
          '入职日期': 'timeOfEntry',
          '手机号': 'mobile',
          '姓名': 'username',
          '转正日期': 'correctionTime',
          '工号': 'workNumber'
        }
        //   console.log(header, results)
        const data = []
        results.forEach(item => {
          // 调用批量导入接口，需要注意对象数组，对象的键必须是英文
          // 但我们导入的对象是中文 所以要处理
          // 先把body的数据，对象数组拼出来
          // console.log(item)
          const obj = {}
          for (const key in item) {
            const englishKey = userRelations[key]
            console.log(englishKey)
            // 等价于 if (['timeOfEntry','correctionTime']..includes(englishKey)
            if (englishKey === 'timeOfEntry' || englishKey === 'correctionTime') {
              obj[englishKey] = this.formatExcelDate(item[key])
            } else {
              obj[englishKey] = item[key]
            }

            // console.log(key, item[key])
          }
          data.push(obj)
        })
        // console.log(data)
        await reqImportEmployee(data)
        this.$router.back()
      }
    }
  }
}
</script>

<style>

</style>
